package org.ume.school.modules.acticles;

import com.bluesimon.wbf.*;
import com.bluesimon.wbf.authentication.Authentication;
import org.ume.school.modules.model.ErrorTag;
import org.ume.school.modules.model.entity.Goods;
import org.ume.school.modules.model.entity.Comment;
import org.ume.school.modules.model.entity.Thumbup;
import com.bluesimon.wbf.usercenter.User;
import com.bluesimon.wbf.usercenter.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Django on 2017/7/15.
 */
@RestController
@RequestMapping("/v0.1/article")
public class ArticleController {

    @Resource
    private ArticleService articleService;

    @Resource
    private UserService userService;


    /**
     * 翻页查看全部数据
     *
     * @param offset
     * @param limit
     * @param orderby
     * @param direction
     * @return
     */
    @RequestMapping("/all")
    public Response<Page<Goods>> getArticles(@RequestParam(value = "offset", required = true) String offset,
                                             @RequestParam(value = "limit", required = true) String limit,
                                             @RequestParam(value = "orderby", defaultValue = "", required = false) String orderby,
                                             @RequestParam(value = "direction", defaultValue = "", required = false) String direction) {
        Page<Goods> articles = articleService.findAll(offset, limit, orderby, direction);
        return new Response<>(articles);
    }

    /**
     * 翻页查看全部数据
     *
     * @param offset
     * @param limit
     * @param orderby
     * @param direction
     * @return
     */
    @RequestMapping("/bytype")
    public Response<Page<Goods>> getArticlesByType(@RequestParam(value = "offset", required = true) String offset,
                                                   @RequestParam(value = "limit", required = true) String limit,
                                                   @RequestParam(value = "orderby", defaultValue = "", required = false) String orderby,
                                                   @RequestParam(value = "direction", defaultValue = "", required = false) String direction,
                                                   @RequestParam(value = "type", defaultValue = "", required = false) String type) {
        Page<Goods> articles = articleService.findAllByType(offset, limit, orderby, direction, type);
        return new Response<>(articles);
    }

    @RequestMapping("/{article_id}")
    public Response<Goods> getArticlesById(@PathVariable("article_id") String articleId) {
        Goods article = articleService.findById(articleId);
        return new Response<>(article);
    }

    /**
     * 获取作者的文章
     *
     * @param userId
     * @return
     */
    @RequestMapping("/author/{user_id}")
    public Response<List<Goods>> getArticlesByAuthor(@PathVariable("user_id") String userId) {
        List<Goods> article = articleService.findByUserId(userId);
        return new Response<>(article);
    }

    /**
     * 获取推荐文章
     *
     * @param userId
     * @return
     */
    @RequestMapping("/recommend")
    public Response<List<Goods>> recommendArticle(@RequestParam(value = "user_id", required = false) String userId) {
        List<Goods> article = articleService.findByUserId(userId);
        return new Response<>(article);
    }

    /**
     * 文章点赞
     *
     * @param articleId
     * @param remoteAddr
     * @param user
     * @return
     */
    @RequestMapping(value = "/{article_id}/thumbup", method = RequestMethod.POST)
    public Response<Thumbup> thumbup(@PathVariable("article_id") String articleId,
                                     @Remote RemoteClient remoteAddr,
                                     @Logined IUser user
    ) {
        Thumbup thumbup = new Thumbup();
        thumbup.setGoodsId(articleId);
        thumbup.setId(UUID.randomUUID().toString());
        String who = remoteAddr.getRemoteHost();
        if (null != user) {
            who = user.getId();
        }
        thumbup.setWho(who);
        thumbup = articleService.thumbup(thumbup);
        Response<Thumbup> resp = new Response<>(thumbup);
        if (null == thumbup) {
            resp.setCode(ErrorTag.NOT_ALLOW_THUMBUP.getCode());
            resp.setMessage(ErrorTag.NOT_ALLOW_THUMBUP.getMessage());
        }
        return resp;
    }

    /**
     * 文章评论
     * @param articleId
     * @param comment
     * @param user
     * @return
     */
    @RequestMapping(value = "/{article_id}/comment", method = RequestMethod.POST)
    public Response<Comment> comment(@PathVariable("article_id") String articleId,
                                     @RequestBody Comment comment,
                                     @Logined IUser user) {
        Response<Comment> resp = new Response<>();
        if (null == user) {
            resp.setCode(ErrorTag.INVAILD_USER.getCode());
            resp.setMessage(ErrorTag.INVAILD_USER.getMessage());
        } else {
            comment.setCreateTime(new Date());
            comment.setCommentId(UUID.randomUUID().toString());
            comment.setGoodsId(articleId);
            User u = userService.getUser(user.getId());
            //评论保留昵称
            comment.setUserName(u.getNickName());
            comment.setUserId(u.getId());
            comment.setUserHeadImage(u.getHeadImage());
            comment = articleService.sumbitComment(comment);
            resp.setData(comment);
        }
        return resp;
    }

    /**
     * 获取评论
     * @param articleId
     * @return
     */
    @RequestMapping(value = "/{article_id}/comment", method = RequestMethod.GET)
    public Response<List<Comment>> getCommentById(@PathVariable("article_id") String articleId) {
        Response<List<Comment>> resp = new Response<>();
        List<Comment> list = articleService.getComment(articleId);
        resp.setData(list);
        return resp;
    }

    /**
     * 提交文章
     * @param article
     * @param user
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public Response<Goods> submitArticle(@RequestBody Goods article, @Logined IUser user) {
        Response<Goods> resp = new Response<>();
        if (user == null) {
            resp.setCode(ErrorTag.INVAILD_USER.getCode());
            resp.setMessage(ErrorTag.INVAILD_USER.getMessage());
        } else {
            if (StringUtils.isEmpty(article.getId())) {
                article.setId(UUID.randomUUID().toString());
                article.setCreateTime(new Date());
                article.setUserId(user.getId());
                article.setPvs(0);
                article.setGreats(0);
                article.setCommentCnt(0);

                //设置冗余作者信息
                User u = (User) user;
                article.setUserName(u.getUserName());
                article.setNickName(u.getNickName());
                article.setUserHeadImage(u.getHeadImage());
            } else {
                //文章的创建者不是请求者 并且 这个请求者不是管理员； 就不让删除
                if ((!(user.getId().equals(article.getUserId())))
                        && (!user.getRole().contains("Admin"))) {
                    resp.setCode(ErrorTag.NOT_ALLOW_EDIT.getCode());
                    resp.setMessage(ErrorTag.NOT_ALLOW_EDIT.getMessage());
                } else {
                    if (!StringUtils.isEmpty(article.getTags())) {
                        List<String> tags = Arrays.asList(article.getTags().split(","));
                        article.setTagList(tags);
                    }
                    Goods list = articleService.submitArticle(article);
                    resp.setData(list);
                }
            }
        }
        return resp;
    }

    /**
     * 根据用户查询文章
     *
     * @param offset
     * @param limit
     * @param orderby
     * @param direction
     * @return
     */
    @RequestMapping("/byuser")
    public Response<Page<Goods>> getArticlesByUser(@RequestParam(value = "offset", required = true) String offset,
                                                   @RequestParam(value = "limit", required = true) String limit,
                                                   @RequestParam(value = "orderby", defaultValue = "", required = false) String orderby,
                                                   @RequestParam(value = "direction", defaultValue = "", required = false) String direction,
                                                   @RequestParam(value = "user_id", defaultValue = "", required = true) String userId) {
        Page<Goods> articles = articleService.findByUserId(offset, limit, orderby, direction, userId);
        return new Response<>(articles);
    }


    /**
     * 获取优秀文章给首页
     * 1、点赞多的
     * 2、专家评论的
     * 12条 ； 可以缓存    greats最多
     */
    @RequestMapping(value = "/excellents", method = RequestMethod.GET)
    public Response<List<Goods>> getExcellents() {
        List<Goods> articles = articleService.findExcellents();
        return new Response<>(articles);
    }
}
